package com.example.managemyself.ui.auth;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.managemyself.MainActivity;
import com.example.managemyself.R;
import com.example.managemyself.data.model.User;
import com.example.managemyself.ui.admin.AdminMainActivity;
import com.example.managemyself.util.UserManager;
import com.google.android.material.textfield.TextInputEditText;

public class LoginActivity extends AppCompatActivity {

    private TextInputEditText etUsername;
    private TextInputEditText etPassword;
    private Button btnLogin;
    private TextView tvRegister;
    private TextView tvForgotPassword;
    private ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // 初始化视图
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        btnLogin = findViewById(R.id.btnLogin);
        tvRegister = findViewById(R.id.tvRegister);
        tvForgotPassword = findViewById(R.id.tvForgotPassword);
        progressBar = findViewById(R.id.progressBar);

        // 检查用户是否已登录
        if (UserManager.getInstance().isLoggedIn()) {
            startAppropriateActivity();
            return;
        }

        // 设置登录按钮点击事件
        btnLogin.setOnClickListener(v -> login());

        // 设置注册文本点击事件
        tvRegister.setOnClickListener(v -> {
            Intent intent = new Intent(this, RegisterActivity.class);
            startActivity(intent);
        });
        
        // 设置忘记密码文本点击事件
        tvForgotPassword.setOnClickListener(v -> {
            Intent intent = new Intent(this, ForgotPasswordActivity.class);
            startActivity(intent);
        });
    }

    /**
     * 登录
     */
    private void login() {
        // 获取输入
        String username = etUsername.getText().toString().trim();
        String password = etPassword.getText().toString().trim();

        // 验证输入
        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (password.isEmpty()) {
            etPassword.setError("请输入密码");
            etPassword.requestFocus();
            return;
        }

        // 显示加载状态
        showLoading(true);

        // 调用登录API
        UserManager.getInstance().login(this, username, password, new UserManager.AuthCallback() {
            @Override
            public void onSuccess(User user) {
                runOnUiThread(() -> {
                    showLoading(false);
                    startAppropriateActivity();
                });
            }

            @Override
            public void onError(String error) {
                runOnUiThread(() -> {
                    showLoading(false);
                    Toast.makeText(LoginActivity.this, error, Toast.LENGTH_LONG).show();
                    // 清空密码
                    etPassword.setText("");
                });
            }
        });
    }

    /**
     * 显示/隐藏加载状态
     */
    private void showLoading(boolean isLoading) {
        if (isLoading) {
            progressBar.setVisibility(View.VISIBLE);
            btnLogin.setEnabled(false);
        } else {
            progressBar.setVisibility(View.GONE);
            btnLogin.setEnabled(true);
        }
    }

    /**
     * 根据用户角色启动相应的活动
     */
    private void startAppropriateActivity() {
        User currentUser = UserManager.getInstance().getCurrentUser();
        Intent intent;
        
        if (currentUser != null && currentUser.isAdmin()) {
            // 管理员用户跳转到管理员界面
            intent = new Intent(this, AdminMainActivity.class);
            Toast.makeText(this, "欢迎，管理员 " + currentUser.getDisplayName(), Toast.LENGTH_SHORT).show();
        } else {
            // 普通用户跳转到普通用户界面
            intent = new Intent(this, MainActivity.class);
            if (currentUser != null) {
                Toast.makeText(this, "欢迎回来，" + currentUser.getDisplayName(), Toast.LENGTH_SHORT).show();
            }
        }
        
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
    }
    
    /**
     * 启动主活动（保留兼容性）
     */
    private void startMainActivity() {
        startAppropriateActivity();
    }
} 